package com.mdms.commands.user;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Hibernate;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import com.mdms.commands.BaseCommand;
import com.mdms.dto.UdtPremits;
import com.mdms.dto.UdtSelections;
import com.mdms.dto.UdtUsers;
import com.mdms.interfaces.orm.CrudDAO;
import com.mdms.logger.SimplyMDLogger;

public class GetUserRights extends BaseCommand {


	private static final long serialVersionUID = 1L;

	private final static SimplyMDLogger logger = new SimplyMDLogger(GetUserRights.class);

	private Long user_id;

	private Map<String,String> rightsMap;



	@Override
	public void execute() throws Exception {
		logger.debug("execute", "START");

		CrudDAO crudDAO = getDaoFactory().getCrudDAO();
		crudDAO.setPersistentClass(UdtPremits.class);
		
		if(user_id!=null){
			Transaction tx= crudDAO.beginTransaction();
			List criterion = new ArrayList();
			criterion.add(Restrictions.eq("udtUsers.usr_id", user_id));
			List <UdtPremits>result = crudDAO.findByCriterions(criterion);
			
			if (result != null && result.size() > 0) {
				for (UdtPremits udtPremits : result) {
					Hibernate.initialize(udtPremits.getUdtRights());
				}
				tx.commit();
				prepareRightsMap(result);
				

			}else{
				this.errorCode=-1;
				this.errorDesc="MESSAGE FROM BUNDLE USER NOT FOUND";
			}
			
		}

		logger.debug("execute", "STOP");

	}

	private void prepareRightsMap(List<UdtPremits> premits){
		logger.debug("prepareRightsMap", "START");
		rightsMap = new HashMap<String,String>();
		for (UdtPremits udtPremits : premits) {
			//Hibernate.initialize(udtPremits);
			if(udtPremits.getUdtRights()!=null){
				String rightName=udtPremits.getUdtRights().getRgt_name();
				if(rightName!=null){
					rightsMap.put(rightName, rightName);
				}
			}else if(udtPremits.getUdtRgtGroups()!=null){
				Long grpId=udtPremits.getUdtRgtGroups().getGop_id();
				CrudDAO crudDAO = getDaoFactory().getCrudDAO();
				crudDAO.setPersistentClass(UdtSelections.class);
				Transaction tx=crudDAO.beginTransaction();
				List criterion = new ArrayList();
				criterion.add(Restrictions.eq("udtRgtGroups.gop_id",grpId));
				List <UdtSelections>result = crudDAO.findByCriterions(criterion);
				if (result != null && result.size() > 0) {
					for (UdtSelections udtSelections : result) {
						Hibernate.initialize(udtSelections);
						Hibernate.initialize(udtSelections.getUdtRights());
						String rightName=udtSelections.getUdtRights().getRgt_name();
						if(rightName!=null){
							rightsMap.put(rightName, rightName);
						}
					}
				}
				tx.commit();
			}
		}
		
		logger.debug("prepareRightsMap", "END");
	}

	public void setUser_id(Long user_id) {
		this.user_id = user_id;
	}



	public Map<String, String> getRightsMap() {
		return rightsMap;
	}

}
